package org.projectback.service.AccountService.impl;

import jakarta.annotation.Resource;
import org.projectback.entity.AccountEntity.Account;
import org.projectback.entity.AccountEntity.CustomUser;
import org.projectback.mappers.SearchAccount;
import org.projectback.service.SqlService.impl.SqlServiceImpl;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

@Service
public class LoginServiceImpl implements UserDetailsService {
    @Resource
    private SqlServiceImpl searchService;
    @Resource
    private SearchAccount searchAccount;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Account sqlUser = searchService
                .query()
                .eq("username", username)
                .or()
                .eq("email", username)
                .one();
        if (sqlUser == null) {
            throw new UsernameNotFoundException("user not found");
        }
        CustomUser loginUser = new CustomUser();
        loginUser.setUsername(sqlUser.getUsername());
        loginUser.setPassword(sqlUser.getPassword());
        loginUser.setEmail(sqlUser.getEmail());
        loginUser.setPhone(sqlUser.getPhone());
        loginUser.setRole(sqlUser.getRole());
        loginUser.setId(sqlUser.getId());
        return loginUser;
    }
}
